package src.com.qf.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import src.com.qf.dao.OrderDao;
import src.com.qf.entity.Order;
import src.com.qf.utils.JdbcUtil;

import java.sql.SQLException;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    private QueryRunner queryRunner = new QueryRunner();
    @Override
    public void insertOrder(Order order) {
        String sql = "insert into tb_order(orderNum,orderSum,orderTime,orderStatus,aid,uid) values(?,?,?,?,?,?)";
        try {
            //获取自增长主键id
            ResultSetHandler rs = new ScalarHandler();
            long insert = (long) queryRunner.insert(JdbcUtil.getCon(),sql,rs,order.getOrderNum(),order.getOrderSum(),order.getOrderTime(),order.getOrderStatus(),order.getAid(),order.getUid());
            order.setId((int)insert);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Order> selectOrdersByUid(Integer id) {
        String sql = "select *from tb_order where uid = ?";
        List<Order> query = null;
        try {
            query = queryRunner.query(JdbcUtil.getCon(), sql, new BeanListHandler<>(Order.class), id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    @Override
    public Order selectOrdersById(Integer strOid) {
        String sql = "select *from tb_order where id = ?";
        Order query = null;
        try {
            query = queryRunner.query(JdbcUtil.getCon(), sql, new BeanHandler<>(Order.class), strOid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }
}
